/*
 * @copyright 2010 Gerald Jacobson
 * @license GNU General Public License
 * 
 * This file is part of My Quick Rules.
 *
 * My Quick Rules is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * My Quick Rules is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with My Quick Rules.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.amphiprion.myquickrules.dao;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.amphiprion.myquickrules.Home;
import org.amphiprion.myquickrules.entity.MainRule;
import org.amphiprion.myquickrules.entity.Overview;
import org.amphiprion.myquickrules.entity.Phase;
import org.amphiprion.myquickrules.entity.PhaseList;
import org.amphiprion.myquickrules.util.ApplicationConstants;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;

/**
 * @author Amphiprion
 * 
 */
public class MainRuleDao extends AbstractDao {
	private static MainRuleDao instance;

	public static MainRuleDao getInstance() {
		if (instance == null) {
			instance = new MainRuleDao();
		}
		return instance;
	}

	public MainRule getMainRule(String gameId) {
		HashMap<String, Bitmap> bitmaps = new HashMap<String, Bitmap>();
		// String lng = Locale.getDefault().getLanguage();
		try {
			File f = new File(Environment.getExternalStorageDirectory() + "/" + ApplicationConstants.DIRECTORY + "/" + gameId + "/main.xml");

			InputStream is = null;
			if (f.exists()) {
				is = new FileInputStream(f);
			}
			if (is == null) {
				is = Home.class.getResourceAsStream("/" + gameId + "/main.xml");
			}

			DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
			builderFactory.setNamespaceAware(true);

			DocumentBuilder builder = builderFactory.newDocumentBuilder();
			Document document = builder.parse(is);
			is.close();

			NodeList list = document.getElementsByTagName("gamerule");
			Element gameRuleNode = (Element) list.item(0);
			MainRule mr = new MainRule();
			mr.id = gameId;
			mr.setWidth(Float.parseFloat(getAttribute(gameRuleNode, "width", "480")));
			mr.setHeight(Float.parseFloat(getAttribute(gameRuleNode, "height", "800")));
			mr.loopOnPhase = "true".equals(getAttribute(gameRuleNode, "loopOnPhase", "true"));

			// overview
			list = document.getElementsByTagName("overview");
			if (list != null && list.getLength() > 0) {
				Element overviewNode = (Element) list.item(0);

				String filename = getAttribute(overviewNode, "file", null);
				String bg = getAttribute(overviewNode, "background", null);

				Overview o = new Overview();
				o.filename = filename;
				o.backgroundName = bg;
				if (bg != null) {
					Bitmap bitmap = bitmaps.get(bg);
					if (bitmap == null) {
						File fb = new File(Environment.getExternalStorageDirectory() + "/" + ApplicationConstants.DIRECTORY + "/" + gameId + "/" + bg);

						InputStream isb = null;
						if (fb.exists()) {
							isb = new FileInputStream(fb);
						}
						if (isb == null) {
							isb = MainRuleDao.class.getResourceAsStream("/" + gameId + "/" + bg);
						}
						bitmap = BitmapFactory.decodeStream(isb);
						isb.close();
						bitmaps.put(bg, bitmap);
					}
					o.setBitmap(bitmap);
				}
				o.visibleHeight = Float.parseFloat(getAttribute(overviewNode, "visibleHeight", "0"));
				if (filename != null) {
					o.html = getHtml(gameId, o.filename);
				}
				mr.setOverview(o);
			}

			// phases
			list = document.getElementsByTagName("phase");
			if (list != null && list.getLength() > 0) {
				PhaseList phases = new PhaseList();
				for (int i = 0; i < list.getLength(); i++) {
					Element phaseNode = (Element) list.item(i);

					Phase p = new Phase();
					p.backgroundName = getAttribute(phaseNode, "background", null);
					p.filename = getAttribute(phaseNode, "file", null);
					// if (bg != null) {
					// Bitmap bitmap = bitmaps.get(bg);
					// if (bitmap == null) {
					// File fb = new
					// File(Environment.getExternalStorageDirectory() + "/" +
					// ApplicationConstants.DIRECTORY + "/" + gameId + "/" +
					// bg);
					//
					// InputStream isb = null;
					// if (fb.exists()) {
					// isb = new FileInputStream(fb);
					// }
					// if (isb == null) {
					// isb = MainRuleDao.class.getResourceAsStream("/" + gameId
					// + "/" + bg);
					// }
					// bitmap = BitmapFactory.decodeStream(isb);
					// isb.close();
					// bitmaps.put(bg, bitmap);
					// }
					// p.bitmap = bitmap;
					// }
					phases.add(p);
					if (p.filename != null) {
						p.html = getHtml(gameId, p.filename);
					}
				}
//				is.close();
				// o.setParagraphs(getParagraphs(gameId, "overview.xml"));
				if (phases.size() > 0) {
					mr.setPhases(phases);
				}
			}
			return mr;
		} catch (Throwable e) {
			Log.e(ApplicationConstants.PACKAGE, "", e);
			return null;
		}
	}

	private String getHtml(String gameId, String filename) throws Exception {
		File f = new File(Environment.getExternalStorageDirectory() + "/" + ApplicationConstants.DIRECTORY + "/" + gameId + "/" + filename);

		InputStream is = null;
		if (f.exists()) {
			is = new FileInputStream(f);
		}
		if (is == null) {
			is = Home.class.getResourceAsStream("/" + gameId + "/" + filename);
		}
		if (is == null) {
			return null;
		}
		InputStreamReader reader = new InputStreamReader(is);
		BufferedReader bufferReader = new BufferedReader(reader);
		StringBuffer buffer = new StringBuffer();
		String line;
		while ((line = bufferReader.readLine()) != null) {
			buffer.append(line);
			buffer.append("\n");
		}
		is.close();
		return buffer.toString();
	}
}
